package mashibing.class5;

import util.MathUtil;

import java.util.Arrays;

/**
 * 快速排序
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2023-03-23
 */
public class Class5_3_QuickSorted {

    public static void quickSorted(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        partition(arr, 0, arr.length - 1);
    }

    public static void partition(int[] arr, int L, int R) {
        if (L >= R) {
            return;
        }
        MathUtil.swap(arr, L + (int) (Math.random() * (R - L + 1)), R);
        int[] quick = quick(arr, L, R);
        partition(arr, L, quick[0] - 1);
        partition(arr, quick[1] + 1, R);
    }

    // <
    public static int[] quick(int[] arr, int L, int R) {
        int less = L - 1;
        int more = R;
        int num = arr[R];
        int index = L;
        while (index < more) {
            if (arr[index] == num) {
                index++;
            } else if (arr[index] < num) {
                MathUtil.swap(arr, index++, ++less);
            } else {
                MathUtil.swap(arr, index, --more);
            }
        }
        MathUtil.swap(arr, more, R);
        return new int[]{less + 1, more - 1};
    }

    public static void main(String[] args) {
        int[] arr = {7, 7, 2, 9};
        System.out.println(Arrays.toString(arr));
        quickSorted(arr);
        System.out.println(Arrays.toString(arr));
    }
}
